<?php
namespace App\Http\Controllers;

use App\Http\Model\Hint;
use App\Http\Model\OutJson;
use App\Http\Services\ConfigServices;
use App\Http\Services\PhoneNumberServices;
use App\Http\Services\SendPhoneNumberServices;
use App\Http\Services\SendPhoneUserPearlServices;
use App\Http\Services\SendPhoneUserServices;
use App\Http\Services\SendPhoneUserSiteServices;
use App\Http\Services\UserServices;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Mockery\CountValidator\Exception;


class SendPhoneController extends BaseController
{
    protected $sendPhoneNumberServices;
    protected $sendPhoneUserServices;
    protected $sendPhoneUserSiteServices;
    protected $sendPhoneUserPearlServices;
    protected $userServices;
    protected $configServices;

    public function __construct()
    {
        $this->sendPhoneNumberServices = new SendPhoneNumberServices();
        $this->sendPhoneUserServices = new SendPhoneUserServices();
        $this->sendPhoneUserSiteServices = new SendPhoneUserSiteServices();
        $this->sendPhoneUserPearlServices = new SendPhoneUserPearlServices();
        $this->userServices = new UserServices();
        $this->configServices = new ConfigServices();
    }

    /*
    * 获取手机号码列表
    * */
    public function getPhoneList(Request $request)
    {
        $res = $this->sendPhoneNumberServices->getList($request);
        OutJson::outJsonResult(Hint::SUCCESS, $res);
    }


    /*
     * 判断用户首次点击
            200;//首次点击
            201;//未充值
            202;//已经领取
            203;//领取等级不符合
            204;//符合领取条件
            205;//用户领取暂缓区 可以填写表单
            206;//手机号码已经被领取
            207;//已经被抢走
            208;//已经有锁定电话号码
            209;//领取为首次领取
     * */
    public function firstClick(Request $request)
    {
        $user_id = $request->input('user_id');
        $rank = $request->input('rank') ?? 1;
        $phone_id = $request->input('phone_id') ?? '';

        $config = $this->configServices->getConfig(2);
        $checkDate = $this->configServices->checkConfigDate($config['send_phone_date'],time());
        if(!$checkDate){
            $res['code'] = '210';
            OutJson::outJsonResult(Hint::SUCCESS, $res);
        }
        if (!$user_id) {
            OutJson::outJsonResult(Hint::PARAM_ERROR, []);
        }
        $checkUser = $this->userServices->inviteUserToNewUser($user_id);
        if (!$checkUser) {
            OutJson::outJsonResult(Hint::USER_INFO_NO_EXIST);
        }
        $code = $this->sendPhoneUserServices->verifyUser($checkUser['user_id'], $rank);
        $res['code'] = $code;
        $res['status'] = $rank;
        if ($code == 204) {
            $checkCode = $this->sendPhoneUserServices->checkUserPhone($checkUser['user_id'], $phone_id);
            if ($checkCode['code'] == 208) {
                $res['code'] = 208;
                $res['phone'] = $checkCode['phone'];
            } else {
                $res['code'] = $checkCode;
            }
        }
        OutJson::outJsonResult(Hint::SUCCESS, $res);
    }


    public function affirmPhone(Request $request)
    {
        $user_id = $request->input('user_id');
        $phone_id = $request->input('phone_id');
        //暂缓领取号码
        $res['code'] = $this->sendPhoneNumberServices->set_phone_cache($user_id, $phone_id);
        if ($res['code'] == 208) {
            $user = "SENDPHONE:" . $user_id;
            $hashUserAll = Redis::hgetall($user);
            $res['phone'] = $hashUserAll['phone'];
        }
        OutJson::outJsonResult(Hint::SUCCESS, $res);
    }


    /*
     * 监听充值
     *  {\"user_id\":347,\"diamond_amount\":499900,\"pay_type\":6,\"pay_timestamp\":1562580400,\"pearl_amount\":0,\"recharge_type\":0}
     *  $body['user_id'] = 347;
        $body['diamond_amount'] = 499900;
        $body['change_timestamp'] = '1562569596';
        $body['pay_type'] = 6;
        $body['recharge_type'] = 0;
    * */
    public function listenUserRecharge($body)
    {
        $body = json_decode($body, true);
        $user_id = $body['user_id'] ?? 0;
        $diamond_amount = $body['diamond_amount'] ?? 0;
        $timestamp = $body['change_timestamp'] ?? 0;
        $diamond_num_type = ['1' => '64800', '2' => '199800', '3' => '499900'];

        //支付类型 --- 0.支付宝 1.微信 2.苹果内购 3.android公号 4.IOS公众号 5.后台代充 6.支付宝wap端充值 7.微信wap端充值
        $pay_array = [6, 7];
        $pay_type = $body['pay_type'];
        if ($body['recharge_type'] == 1) false;
        if (empty($user_id) || empty($diamond_amount)) {
            write_log('sendPhoneConsumer', 'bodyError', json_encode($body));//数据错误
            return false;
        }
        $config = $this->configServices->getConfig(2);
        //判断充值类型
        if (!in_array($pay_type, $pay_array)) {
            write_log('sendPhoneConsumer', 'payTypeError', json_encode($body));//支付类型错误
            return false;
        }
        //判定用户充值等级
        if (!in_array($diamond_amount, $diamond_num_type)) {
            write_log('sendPhoneConsumer', 'rechargeStandard', json_encode($body));//不达标
            return false; //充值不达标
        }
        $config_date = $config['send_phone_date'];
        $diamond_num_type = array_flip($diamond_num_type);
        $pearl_rank = $diamond_num_type[$diamond_amount];//充值等级
        //认证用户资格 -- 判断用户是否参与活动&活动是否过期&充值与获取活动资格时间戳判断
        $user_info = $this->sendPhoneUserServices->getUser($user_id, $config_date, $timestamp, $pearl_rank);
        if (!$user_info) {
            return false;
        }
        $config_pearl = explode(',', $config['send_phone_pearl_num']['value']);
        $recharge_data['pearl_num'] = $config_pearl[$pearl_rank - 1];
        $recharge_data['user_id'] = $user_id;
        $recharge_data['msg'] = '领取手机号充值金豆';
        $pearl_api = json_decode(curl_request(env('KK_API_HOST') . '/finance/pearl/recharge', $recharge_data), true);
        if ($pearl_api['code'] !== 0) {
            //充值失败 销毁队列
            write_log('sendPhoneConsumer', 'pearlApiError', json_encode($recharge_data));
            return false;
        }
        //添加记录
        $pearl_data['user_id'] = $user_id;
        $pearl_data['award_pearl'] = $config_pearl[$pearl_rank - 1];
        $log = $this->sendPhoneUserPearlServices->createLog($pearl_data);
        if (!$log) write_log('sendPhoneConsumer', 'pearlLogError', json_encode($pearl_data));

//        更改用户资格为可领取状态
        $editUser = $this->sendPhoneUserServices->editUser($user_id, $pearl_rank);
        if (!$editUser) {
            write_log('sendPhoneConsumer', 'editUserStatusError', json_encode($recharge_data));
            return false;
        }
        write_log('sendPhoneConsumer', 'success', json_encode($recharge_data));
        return true;
    }


    /*
     * 用户地址
     * */
    public function userSite(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_id' => 'bail|string|required',
            'phone_id' => 'bail|integer|required',
            'name' => 'bail|string|required',
            'user_phone' => 'bail|required|digits:11',
            'site' => 'bail|required',
        ], [
            'user_id.required' => '用户信息错误',
            'phone_id.required' => '靓号信息错误',
            'name.required' => '请输入收件人姓名',
            'user_phone.digits' => '手机账号有误请重新输入',
            'user_phone.required' => '请输入收件人手机号',
            'site.required' => '请输入收件人地址',
        ]);
        if ($validator->fails()) {
            $res['code'] = -1;
            $res['msg'] = $validator->errors()->all()[0];
            OutJson::outJsonResult(Hint::SUCCESS, $res);
        }
        $data = $request->post();
        $checkUser = $this->userServices->inviteUserToNewUser($data['user_id']);
        if (!$checkUser) {
            OutJson::outJsonResult(Hint::USER_INFO_NO_EXIST);
        }
        $res = $this->sendPhoneUserSiteServices->createSite($data);
        if (!$res) OutJson::outJsonResult(Hint::ERROR);
        OutJson::outJsonResult(Hint::SUCCESS);
    }

}
